package cn.com.infcn.monitor.task.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

import org.apache.log4j.Logger;

import cn.com.infcn.monitor.bean.IFCJVMMemory;
import cn.com.infcn.monitor.bean.IFCJVMMemoryUsage;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * Java 虚拟机内存系统的管理接口。
 * 堆内存
 * Eden、Survivor、 Old Gen
 * 非堆内存
 * Code Cache、 Perm Gen
 * @author jijs
 *
 */
public class JVMMemoryTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(JVMMemoryTask.class);

	@Override
	public IFCJVMMemory execute() throws Exception {
		return jvmMemory();
	}

	public IFCJVMMemory jvmMemory() {
		IFCJVMMemoryUsage ifcHeapMemoryUsage = null;

		try {
			MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

			// 堆内存
			ifcHeapMemoryUsage = new IFCJVMMemoryUsage();
			MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
			IFCBeanUtils.copyProperties(heapMemoryUsage, MemoryUsage.class, ifcHeapMemoryUsage);

			// 非堆内存
			IFCJVMMemoryUsage ifcNonHeapMemoryUsage = new IFCJVMMemoryUsage();
			MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
			IFCBeanUtils.copyProperties(nonHeapMemoryUsage, MemoryUsage.class, ifcNonHeapMemoryUsage);

			IFCJVMMemory ifcMemory = new IFCJVMMemory();
			ifcMemory.setHeapMemoryUsage(ifcHeapMemoryUsage);
			ifcMemory.setNonHeapMemoryUsage(ifcNonHeapMemoryUsage);
			ifcMemory.setIsVerbose(memoryMXBean.isVerbose());
			ifcMemory.setObjectPendingFinalizationCount(memoryMXBean.getObjectPendingFinalizationCount());

			return ifcMemory;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}
		return null;
	}
	
	/*private void copyProperties(MemoryUsage heapMemoryUsage, IFCJVMMemoryUsage ifcHeapMemoryUsage){
		ifcHeapMemoryUsage.setCommitted(heapMemoryUsage.getCommitted());
		ifcHeapMemoryUsage.setInit(heapMemoryUsage.getInit());
		ifcHeapMemoryUsage.setMax(heapMemoryUsage.getMax());
		ifcHeapMemoryUsage.setUsed(heapMemoryUsage.getUsed());
	}*/

	public static void main(String[] args) {
		JVMMemoryTask task = new JVMMemoryTask();
		try {
			task.jvmMemory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
